Scope Mini Lesson: Local and Global Scopes of Python Variables

In Python, scoping determines the access range of variables, mainly divided into two types: local and global. **Local Scope**: Variables defined inside a function are only valid within that function (e.g., `age = 18`). If a variable with the same name as a global variable is defined inside a function, it will be treated as a local variable first (e.g., `x = 200` overwrites the global `x=100`, but the global `x` remains 100 externally). **Global Scope**: Variables defined outside a function are accessible throughout the entire program (e.g., `name = "Xiao Ming"`). There is no issue with direct access. However, if a function intends to modify a global variable, it must be declared with `global` (e.g., `global score`); otherwise, Python will mistakenly treat it as a local variable (e.g., `score=90` does not modify the original global value of 80). **Nested Functions**: The inner function can access the local variables of the outer function. When modifying these variables, the `nonlocal` declaration is required (e.g., `nonlocal outer_var`). Summary of Rules: Local scope is limited to the function, global scope spans the entire program; use `global` to modify global variables and `nonlocal` to modify outer local variables. Proper use of scoping can avoid variable conflicts and enhance code readability.

Read More